from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
import hashlib
from .models import *
from .forms import UserForm
import random


# Create your views here.


def set_password(password):
    md5 = hashlib.md5(password.encode())
    return md5.hexdigest()


def LoginVaild(func):
    def inner(request, *args, **kwargs):
        username = request.COOKIES.get("username")
        user_id = request.COOKIES.get("userid")
        if username and user_id:
            user = QUser.objects.get(id=int(user_id))
            if user.username == username:
                return func(request, *args, **kwargs)
        else:
            return HttpResponseRedirect("/login/")
        return func(request, *args, **kwargs)

    return inner


def reqtest(request):
    return render_to_response("reqtest.html", locals())


def register(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = set_password(request.POST.get("password"))
        QUser.objects.create(username=username, password=password)
        return HttpResponseRedirect("/login/")
    return render(request, "register.html")


def login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = set_password(request.POST.get("password"))
        user = QUser.objects.filter(username=username, password=password).first()
        if user:
            rep = HttpResponseRedirect("/index/")
            rep.set_cookie("userid", user.id)
            rep.set_cookie("username", user.username)
            request.session["UID"] = user.id
            return rep
    return render(request, "login.html", {"msg": "账号或者用户名错误"})


def logout(request):
    rep = HttpResponseRedirect("/login/")
    rep.delete_cookie("username")
    rep.delete_cookie("userid")
    del request.session["UID"]
    return rep


def base(request):
    return render(request, "base.html")


@LoginVaild
def user_info(request):
    # 个人中心
    if request.method == "POST":
        user = QUser.objects.filter(id=1)  # 暂时用id=1来测试
        user.picture = request.FILES.get("picture")

        if user.picture:
            user.update(picture=user.picture)

        user.nick_name = request.POST.get("nick_name")
        if user.nick_name:
            user.update(nick_name=user.nick_name)

        user.gender = request.POST.get("gender")
        if user.gender:
            user.update(gender=user.gender)

        user.phone = request.POST.get("phone")
        if user.phone:
            user.update(phone=user.phone)

        user.email = request.POST.get("email")
        if user.email:
            user.update(email=user.email)

        user.address = request.POST.get("address")
        if user.address:
            user.update(address=user.address)
    return render(request, "user_info.html", locals())


@LoginVaild
def registerform(request):
    user_form = UserForm()
    if request.method == "POST":
        user_form_temp = UserForm(request.POST)
        if user_form_temp.is_valid():
            data = user_form_temp.cleaned_data  # 校验之后的数据
            print("通过", data)
        else:
            errors = user_form_temp.errors
            print("不通过", errors)

    return render(request, "registerform.html", locals())


def cookietest(request):
    rep = HttpResponse("cookie操作")
    # 设置cookies
    # rep.set_cookie("username","zhangsan")
    # rep.set_cookie("userid","123")

    # 获取cookies
    # username = request.COOKIES.get("username")
    # print(username)

    # 删除cookies
    rep.delete_cookie("username")
    rep.delete_cookie("userid")
    print(rep.cookies)
    print("___")
    return rep


def sessiontest(request):
    # session的操作，session 存储在数据库中

    # session 的设置
    # request.session["ID"] = "1234"

    # session 的获取
    # sid = request.session.get("ID")
    # print(sid)

    # session 的删除
    sid = request.session.get("ID")
    del (sid)

    return HttpResponse("session操作")


@LoginVaild
def index(request):
    return render(request, "index.html")


# 20200608
def list(request):
    return render(request, "list.html")


def add(request):
    ## 添加店铺
    store = Store.objects.create(s_name="生鲜店", s_logo="1.jpg", s_address="北京", s_description="北京生鲜店",
                                 s_user=QUser.objects.get(id=1))
    ## 添加类型
    goodstype = GoodsType.objects.create(t_name="生鲜", t_description="生鲜店")
    ## 增加100 条  
    goods_name = "芹菜、西芹、菠菜、香菜、茼蒿、茴香、生菜、苋菜、莴苣、葱、香葱、分葱、胡葱、楼子葱、蒜头、洋葱头、韭菜、韭葱、黄瓜、丝瓜、冬瓜、菜瓜、苦瓜、南瓜、栉瓜、西葫芦、葫芦、瓠瓜、节瓜、越瓜、笋瓜、佛手瓜"
    goods_name = goods_name.split("、")
    address = "北京市，天津市，上海市，重庆市，河北省，山西省，辽宁省，吉林省，黑龙江省，江苏省，浙江省，安徽省，福建省，江西省，山东省，河南省，湖北省，湖南省，广东省，海南省，四川省，贵州省，云南省，陕西省，甘肃省，青海省，台湾省"
    address = address.split("，")
    for n in range(10):
        for i, j in enumerate(range(10), 1):  ## i 是索引 代表下标从1开始
            goods = Goods()
            goods.g_number = str(i).zfill(5)  ## 返回指定长度的字符串   长度是5 
            goods.g_name = random.choice(address) + random.choice(goods_name)  ###从列表中随机取一个值  
            goods.g_price = round(random.random() * 100, 2)  ## 0到1 的小数  
            goods.g_num = random.randint(1, 100)
            goods.g_safe_date = random.randint(1, 12)
            goods.g_description = "很好"
            goods.g_picture = "buyer/images/goods.jpg"
            goods.g_type = goodstype
            goods.g_store = store
            goods.save()
    return HttpResponse("添加数据")


def goods(request):
    # 建立Json请求，提供数据接口。list页面需要商品信息
    goods_list = Goods.objects.all()
    result = {"data": []}
    for goods in goods_list:
        goods_info = {
            "g_picture": str(goods.g_picture),
            "g_name": goods.g_name,
            "g_price": goods.g_price,
        }
        result["data"].append(goods_info)

    return JsonResponse(result)


# FBV 函数视图
from django.views.decorators.csrf import csrf_exempt


@csrf_exempt  # 函数视图csrf 拦截的第一种方式
def goodss(request):
    if request.method == "GET":
        return JsonResponse({"method": "GET"})
    if request.method == "POST":
        return JsonResponse({"method": "POST"})
    if request.method == "PUT":
        return JsonResponse({"method": "PUT"})
    if request.method == "DELETE":
        return JsonResponse({"method": "DELETE"})


# CBV 类视图
from django.views import View
from django.utils.decorators import method_decorator


# 封装部分的类视图中的方法
@method_decorator(csrf_exempt, 'dispatch')
class Goodss(View):

    def __init__(self):
        # 封装统一的返回结果
        self.result = {
            "code": 200,
            "msg": "",
            "method": "",
            "data": [],
        }

    def get(self, request):
        self.result["method"] = "GET"
        return JsonResponse(self.result)
        # return JsonResponse({"method": "get"})

    def post(self, request):
        self.result["method"] = "POST"
        return JsonResponse(self.result)
        # return JsonResponse({"method": "post"})

    def put(self, request):
        self.result["method"] = "PUT"
        return JsonResponse(self.result)
        # return JsonResponse({"method": "put"})

    def delete(self, request):
        self.result["method"] = "DELETE"
        return JsonResponse(self.result)
        # return JsonResponse({"method": "delete"})


# # 序列化第一种方法，继承APIView类
# from rest_framework.views import APIView
# from .serializer import MoreListSerializer
# from rest_framework.response import Response
#
# class MoreListView(APIView):
#
#     def get(self, format=None):
#         goods_type_id = self.request.GET.get("type_id")  # 在路由器后面输入 ？type_id=1
#         goods_list = Goods.objects.filter(g_type_id=int(goods_type_id)).all()[:10]
#         # goods_list = Goods.objects.all()
#         serializer = MoreListSerializer(goods_list, many=True)
#         res = serializer.data
#         return Response(res)


# # 序列化第二种方法：使用mixmins类，提高代码的重用率
# from rest_framework import generics,mixins
# from .serializer import MoreListSerializer
# class MoreListView(mixins.ListModelMixin, generics.GenericAPIView):
#     def get_queryset(self):
#         goods_type_id = self.request.GET.get("type_id")
#         goods_list = Goods.objects.filter(g_type_id=int(goods_type_id)).all()[:10]
#         return goods_list
#
#     serializer_class = MoreListSerializer
#
#     def get(self, *args, **kwargs):
#         # 这里返回的托路径是"http://127.0.0.1:8000/morelistview/media/buyer/images/goods.jpg"
#         return self.list(*args, **kwargs)  # 返回的图片数据，默认添加了根路径，而我们只需要返回数据库中存储的文件路径，解决办法
#
#     # 解决方法：重写get_serializer_context
#     def get_serializer_context(self):
#         return {
#             "view":self  # 返回的是一个数据本身，否则DRF框架会自动给图片添加跟路径，
#             # 把settings下面的MEDIA_URL去掉，图片返回的是"images/goods.jpg",
#             # 不确定MEDIA_URL，图片返回的是"/media/buyer/images/goods.jpg"
#         }

# # 序列化第三种方法：REST框架提供一组已经封装好的通用视图类，进一步减少模块的工作量
# from rest_framework import generics
# from .serializer import MoreListSerializer
# class MoreListView(generics.ListAPIView):
#     def get_queryset(self):
#         goods_type_id = self.request.GET.get("type_id")
#         goods_list = Goods.objects.filter(g_type_id=int(goods_type_id))[:10]
#         return goods_list
#
#     serializer_class = MoreListSerializer
#
#     def get_serializer_context(self):
#         return {
#             "view":"self"
#         }


# 序列化第四种方式：viewSet 对通用的视图类进行进一步的封装
# 这种方式要求对路由有所更改
from .serializer import MoreListSerializer
from rest_framework import viewsets

class MoreListView(viewsets.ReadOnlyModelViewSet):
    def get_queryset(self):
        goods_type_id = self.request.GET.get("type_id")
        goods_list = Goods.objects.filter(g_type_id=int(goods_type_id)).all()
        return goods_list

    serializer_class = MoreListSerializer

    def get_serializer_context(self):
        return {
            "view":self
        }


# 序列化第五种方式：基于第四种方式，使用DRF路由替代Django路由
